﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using Microsoft.Win32;
using System.Collections.Specialized;
using System.Net;
using System.IO;
using System.Net.Sockets;
using System.Runtime.InteropServices;

namespace DKSEO
{
    public partial class Form1 : Form
    {
        WebClient wc;
        Data dt;
        string vetinhid;
        public Form1()
        {
            InitializeComponent();
            wc = new WebClient();
            dt = new Data();
            waveOutGetVolume(IntPtr.Zero, out _savedVolume);
            docghiid();
            runwork4Ever();
        }
        [DllImport("winmm.dll")]
        public static extern int waveOutGetVolume(IntPtr h, out uint dwVolume);
        [DllImport("winmm.dll")]
        public static extern int waveOutSetVolume(IntPtr h, uint dwVolume); uint _savedVolume;

        void docghiid()
        {
            if (string.IsNullOrEmpty(readRegitry("ID")))
            {
                string[] data = getdata(wc, "createnew", machinename()).Split('|');
                if (data.Length == 2)
                {
                    string id = data[1];
                    writeRegitry("ID", id);
                    docghiid();
                }
            }
            else
            {
                string id = readRegitry("ID");
                vetinhid = id;
                if (id != null)
                {
                    string abc = getdata(wc, "getweblink", id + "|" + machinename());
                    if (!string.IsNullOrEmpty(abc))
                    {
                        dt = Function.weblinks(abc);
                        string[] ran = dt.links.random.Split(',');
                        randommin = 5;
                        randommax = 10;
                        if (ran.Length == 2)
                        {
                            try
                            {
                                randommin = int.Parse(ran[0]);
                                randommax = int.Parse(ran[1]);
                            }
                            catch (System.Exception ex) { }
                        }
                    }
                }
            }
        }
        void loaddata(bool isNew)
        {
            string abc = getdata(wc, "getweblink", vetinhid + "|" + machinename());
            if (!string.IsNullOrEmpty(abc))
            {
                dt = Function.weblinks(abc);
                List<Link> links = new List<Link>();
                links = dt.links.links;
                string temp = readRegitry("DKS");
                if (temp == null) temp = "";
                List<int> removels = new List<int>();
                for (int i = 0; i < links.Count; i++) if (temp.Contains(links[i].chitieuId + ",")) { removels.Add(i); }
                for (int i = removels.Count - 1; i >= 0; i--) links.RemoveAt(i);
                dt.links.links = links;
            }
        }
        int randommin { get; set; }
        int randommax { get; set; }
        int index = 0;
        void runwork4Ever()
        {
            while (true)
            {
                if (dt.links != null) break;
            }
            if (dt.links.links != null && dt.links.links.Count > 0) working();
        }
        bool kiemtramoi()
        {
            string date = readRegitry("Date");
            if (date == null) date = "";
            string[] data = getdata(wc, "renew", date).Split('|');
            if (data.Length == 2 && data[0] == "1") { writeRegitry("Date", data[1]); return true; }
            else return false;
        }
        void working()
        {
            Random r = new Random();
            int m = 60000;
            int milisecond = r.Next(randommin * m, randommax * m);
            timer1.Interval = milisecond;
            timer1.Start();
        }

        void runpage(int index)
        {
            try
            {
                if (dt != null)
                {
                    string pageURL = dt.links.links[index].pageURL;
                    string webid = dt.links.links[index].chitieuId;
                    waveOutSetVolume(IntPtr.Zero, 0);
                    webBrowser1.Navigate(pageURL);
                    Console.WriteLine("run--" + index);
                }
            }
            catch (System.Exception ex) { }
        }
        string webids = "";

        void updatelog(string value)
        {
            string data = getdata(wc, "updatelog", value);
            if (data != null && data == "1")
                dt.links.links.RemoveAt(index);
            else
                index++;
        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            Console.WriteLine("run");
            runpage(index);
            timer1.Stop();
            working();

        }

        private void BW_DoWork(object sender, DoWorkEventArgs e)
        {
            string value = dt.links.links[index].chitieuId + "|" + dt.links.links[index].pageId + "|" + GetPublicIP() + "|" + vetinhid;
            updatelog(value);
            webids = return_webid();
            if (kiemtramoi()) { index = 0; docghiid(); webids = ""; loaddata(true); }
            else { writeRegitry("DKS", webids); }
        }
        string return_webid()
        {
            string result = webids;
            try
            {
                string temp = readRegitry("DKS");
                if (temp == null) temp = "";
                string tempid = dt.links.links[index - 1].pageId;
                if (!temp.Contains("" + tempid + ",")) { webids += "" + tempid + ","; }
                result = webids;
            }
            catch (System.Exception ex) { }
            return result;
        }
        private void BW_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            Console.WriteLine(index + "----" + dt.links.links.Count);
            //if (index >= dt.links.links.Count) { index = 0; timer1.Stop(); docghiid(); webids = ""; writeRegitry("DKS", webids); }
            if (index >= dt.links.links.Count) { index = 0; timer1.Stop(); webids = ""; writeRegitry("DKS", webids); Application.Exit(); }
            timer1.Enabled = true;
        }

        private void webBrowser1_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
        {
            timer1.Enabled = false;
            BW.RunWorkerAsync();
        }
        #region Code Net
        //////////////////////////////////////////////////////////////////////////
        //Get Machine Name
        string machinename()
        {
            return System.Environment.MachineName;
        }
        //////////////////////////////////////////////////////////////////////////
        //WEB
        public string getdata(WebClient wc, string input, string value)
        {
            string wc_return = null;
            while (true)
            {
                try
                {
                    byte[] bret = wc.DownloadData("http://dangkhoasoft.com/seo/base/index/" + input + "/" + value);
                    wc_return = Encoding.UTF8.GetString(bret);
                    wc_return = string.IsNullOrEmpty(wc_return) ? null : wc_return;
                    break;
                }
                catch (System.Exception ex) { }
            }
            return wc_return;
        }
        //////////////////////////////////////////////////////////////////////////
        private string subKey = "SOFTWARE\\" + Application.ProductName.ToUpper();
        public string SubKey
        {
            get { return subKey; }
            set { subKey = value; }
        }
        private RegistryKey baseRegistryKey = Registry.CurrentUser;
        public RegistryKey BaseRegistryKey
        {
            get { return baseRegistryKey; }
            set { baseRegistryKey = value; }
        }
        string readRegitry(string KeyName)
        {
            RegistryKey rk = baseRegistryKey;
            RegistryKey sk1 = rk.OpenSubKey(subKey);
            if (sk1 == null) return null;
            else
                try { return (string)sk1.GetValue(KeyName.ToUpper()); }
                catch (Exception e) { return null; }
        }
        bool writeRegitry(string KeyName, object Value)
        {
            try
            {
                RegistryKey rk = baseRegistryKey;
                RegistryKey sk1 = rk.CreateSubKey(subKey);
                sk1.SetValue(KeyName.ToUpper(), Value);
                return true;
            }
            catch (Exception e) { return false; }
        }
        bool deleteRegitry(string KeyName)
        {
            try
            {
                RegistryKey rk = baseRegistryKey;
                RegistryKey sk1 = rk.CreateSubKey(subKey);
                if (sk1 == null) return true;
                else sk1.DeleteValue(KeyName);
                return true;
            }
            catch (Exception e) { return false; }
        }
        public string GetPublicIP()
        {
            String direction = "";
            try
            {
                WebRequest request = WebRequest.Create("http://checkip.dyndns.org/");
                using (WebResponse response = request.GetResponse())
                {
                    using (StreamReader stream = new StreamReader(response.GetResponseStream()))
                    {
                        direction = stream.ReadToEnd();
                    }
                }
                //Search for the ip in the html
                int first = direction.IndexOf("Address: ") + 9;
                int last = direction.LastIndexOf("</body>");
                direction = direction.Substring(first, last - first);
            }
            catch (Exception ex)
            {
                IPHostEntry host;
                host = Dns.GetHostEntry(Dns.GetHostName());
                foreach (IPAddress ip in host.AddressList)
                {
                    if (ip.AddressFamily == AddressFamily.InterNetwork)
                    {
                        direction = ip.ToString();
                    }
                }
            }
            return direction;
        }
        #endregion
    }
}
